package com.cong.security.service.impl;

import com.cong.security.core.social.MySocialUser;
import com.cong.security.entity.Account;
import com.cong.security.mapper.AccountMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Component;

/**
 * @Description 自定义用户名密码登录
 * @Author single-聪
 * @Date 2020/1/7 18:42
 * @Version 1.0.1
 **/
@Slf4j
@Component
public class MyUserDetailsServiceImpl implements UserDetailsService, SocialUserDetailsService {

    @Autowired
    private AccountMapper accountMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return buildUser(username);
    }

    @Override
    public SocialUserDetails loadUserByUserId(String id) throws UsernameNotFoundException {
        return buildUser(id);
    }

    private SocialUserDetails buildUser(String id) {
        Account account = null;
        // 如果id长度为11，即代表用户采用手机号方式登陆系统，手机号即为用户用户名，否则即为第三方账户登录
        if (id.length() == 11) {
            account = accountMapper.loginByPhone(id);
        } else {
            account = accountMapper.loginById(id);
        }
        if (account != null) {
            log.info("用户信息封装:[{}]", account);
            String password = account.getPassword();
            return new MySocialUser(account.getId(), id, password, account.getEnabled(), account.getExpired(), true,
                    account.getLocked(), AuthorityUtils.commaSeparatedStringToAuthorityList(account.getRole()));
        } else {
            return new MySocialUser(id, id, null, false, false, false, false,
                    AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"));
        }
    }
}